package com.example.lte.service;

import com.alibaba.fastjson.JSONObject;
import com.example.lte.config.X509TrustUtil;
import com.example.lte.entity.OperationLogEntity;
import com.example.lte.repo.OperationLogRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lzh
 * @date 2020/10/23 - 14:20
 */
@Service
@Slf4j
public class AsyncServiceImpl implements IAsyncService{

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Resource
    private OperationLogRepo operationLogRepo;


    /**
     * 异步保存日志
     *
     * @param logEntity
     */
    @Async("asyncSaveLogExecutor")
    @Override
    public void saveOperationLogByAsync(OperationLogEntity logEntity) {
        operationLogRepo.save(logEntity);
        log.info("异步保存日志");
    }

    @Async("taskExecutor")
    @Override
    public void sendWebsocketMsgBox(String subscribeUrl, String jsonInfo) {
        System.err.println("send Websocket  MsgBox");
        simpMessagingTemplate.convertAndSend(subscribeUrl, jsonInfo);
    }

    @Async("taskExecutor")
    @Override
    public Future<String> reqChinaZServerInfo() {
        log.info("请求chinaZ获取IP");

        String ip = "";
        String chinaz = "http://ip.chinaz.com";

        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            // 防止屏蔽程序抓取而返回403错误
            urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            ip = m.group(1);
        }

        log.info("chinaZ返回的IP:{}",ip);
        return new AsyncResult<>(ip);
    }



    @Async("taskExecutor")
    @Override
    public Future<String> reqPcOnlineServerInfo() {
        log.info("请求 pconline 获取IP");

        String urlStr = "http://whois.pconline.com.cn/ip.jsp";
        // 从http://whois.pconline.com.cn取得IP所在的省市区信息
        String resultArea ="";
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            // 防止屏蔽程序抓取而返回403错误
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            connection.setConnectTimeout(2000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(33000);// 设置读取数据超时时间，单位毫秒
            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setRequestMethod("GET");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
            // 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            resultArea = buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }

        log.info("pconline返回的IP:{}",resultArea);

        return new AsyncResult<>(resultArea);
    }


    @Async("taskExecutor")
    @Override
    public Future<String> reqToolLuServerInfo() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
        log.info("请求 tool.lu 获取IP");

        String urlStr = "https://ip.tool.lu/";
        String resultArea ="";
        URL url = null;
        //SSL认证
        SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
        sslcontext.init(null, new TrustManager[] { new X509TrustUtil() }, new java.security.SecureRandom());
        HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslsession) {
                System.out.println("WARNING: Hostname is not matched for cert.");
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
        //打开HTTPS连接
        HttpsURLConnection connection = null;
        try {
            url = new URL(urlStr);
            connection = (HttpsURLConnection)url.openConnection(); // 新建连接实例

            // 防止屏蔽程序抓取而返回403错误
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            connection.setConnectTimeout(2000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(33000);// 设置读取数据超时时间，单位毫秒
            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setRequestMethod("GET");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            // 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            resultArea = buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }

        log.info("tool.lu 返回的IP:{}",resultArea);

        return new AsyncResult<>(resultArea);
    }
}
